package atom.ui 
{
	import atom.Atom;
	import atom.error.AtomError;
	import atom.IDestroyable;
	import atom.loader.library.LibraryLoader;
	import atom.net.Link;
	import flash.display.Sprite;
	import flash.events.Event;
	
	/**
	 * ...
	 * @author Jorge Braccini
	 */
	public class View extends Sprite implements IDestroyable {
		
		private var _init:Object 		= { };
		private var _tempInit:Object;
		
		protected var link:Link;
		protected var library:LibraryLoader;
		
		public function View(init:Object = null) {
			super();
			_tempInit = init;
			
			initValues();
			
			if (stage)		initialize();
			else 			addEventListener(Event.ADDED_TO_STAGE, handleInitialize);
			
		}
		
		/////////////////////////////////////////
		// Protected Methods ////////////////////
		/////////////////////////////////////////
		
		protected function initValues():void {
			
		}
		
		protected function initialize():void {
			link 		= Atom.link;
			library 	= Atom.library;
			
			merge(_tempInit);
			
			create();
			invalidate();
		}
		
		protected function create():void {
			subscribe();
		}
		
		protected function draw():void {
			
		}
		
		protected function subscribe():void {
			
		}
		
		protected function unsubscribe():void {
			
		}
		
		protected function error(e:Object):void {
			throw new AtomError(e);
		}
		
		/////////////////////////////////////////
		// Public Methods ///////////////////////
		/////////////////////////////////////////
		
		public function destroy():void {
			unsubscribe();
		}
		
		public function invalidate():void {
			draw();
			update();
		}
		
		public function update():void {
			
		}
		
		/////////////////////////////////////////
		// Properties ///////////////////////////
		/////////////////////////////////////////
		
		protected function get init():Object { 	return _init; }
		
		public var viewParent:ViewContainer;
		
		
		/////////////////////////////////////////
		// Private Methods //////////////////////
		/////////////////////////////////////////
		
		private function merge(obj:Object):void {
			if (obj) for (var p:String in obj) init[p] = obj[p];
		}
		
		private function handleInitialize(e:Event):void { 
			removeEventListener(e.type, arguments.callee);
			initialize();
		}
		
	}

}